<?php

namespace app\app\controller;

include_once ROOT_PATH . "jpush-api-php-client/autoload.php";

use JPush\Client as JPushClient;

class Jpush extends Base
{
    public $jiguangAppIds;

    public function __construct()
    {
        parent::__construct();
        $this->jiguangAppIds = db('banben')->cache('jpush_app_ids', 3600)->column('jpush_app_key,jpush_master_secret,keyname', 'app_id');
    }


    function sednjiaungAndroid($appKey, $masterSecret, $content, $title, $jiGuangIds = [], $extparam = [])
    {
        $jPush = new JPushClient($appKey, $masterSecret);
        $pusher = $jPush->push();
        $pusher->setPlatform(['android']);
        $pusher->options(['apns_production' => true]);

        if ($jiGuangIds === 'all') {
            $pusher->addAllAudience();
        } else {
            //['190e35f7e0f75a1959a','101d855909f662eb7f4','1114a89792194ffb9ea','160a3797c8b44a0304e','13065ffa4ebfb07afdb','100d855909f4b8080c0','1a1018970a10257ca87']
            $pusher->addRegistrationId($jiGuangIds);
        }

        $pusher->androidNotification(
            $content,
            [
                'title' => $title,
                'builder_id' => 0,
                'extras' => $extparam
            ]
        );
        $pusher->options(['apns_production' => true]);
        return $this->doSendJpush($pusher);
    }

    function sednjiaungIOS($appKey, $masterSecret, $content, $title, $jiGuangIds = [], $extparam = [])
    {
        $jPush = new JPushClient($appKey, $masterSecret);
        $pusher = $jPush->push();
        $pusher->setPlatform(['ios']);
        $pusher->options(['apns_production' => true]);
        if ($jiGuangIds === 'all') {
            $pusher->addAllAudience();
        } else {
            //['190e35f7e0f75a1959a','101d855909f662eb7f4','1114a89792194ffb9ea','160a3797c8b44a0304e','13065ffa4ebfb07afdb','100d855909f4b8080c0','1a1018970a10257ca87']
            $pusher->addRegistrationId($jiGuangIds);
        }

        $pusher->iosNotification(
            [
                "title" => $title,
                "subtitle" => '',
                "body" => $content,
            ],
            [
                'content-available' => true,
                'category' => 'jiguang',
                'extras' => $extparam
            ]
        );
        return $this->doSendJpush($pusher);
    }

    function doSendJpush($pusher)
    {
        try {
            $code = 1;
            $return = $pusher->send();
        } catch (\JPush\Exceptions\JPushException $e) {
            // try something else here
            $return = $e->getMessage();
            $code = 0;
        }

        return ['return' => $return, 'code' => $code];
    }


    public function dealJpushTest()
    {

        $pushInfos = [
            [
                'app_id' => 'A6156623228930',
                'jiguang_id' => '18171adc03b41085da5',
                'jishu' => 129,
                'content' => '已更新到第129集',
                'title' => '生生世世',
                'vod_id' => 79865,
                'system_type' => 'ios'
            ],
            [
                'app_id' => 'A6158796075920',
                'jiguang_id' => '1507bfd3f778b808564',
                'jishu' => 129,
                'content' => '已更新到第129集',
                'title' => '生生世世',
                'vod_id' => 79865,
                'system_type' => 'android'
            ],
        ];

        foreach ($pushInfos as $pushInfo) {
            //写入数据库
            $jiguangInfo = $this->jiguangAppIds[$pushInfo['app_id']];
            switch ($pushInfo['system_type']) {
                case 'ios':
                    $return = $this->sednjiaungIOS($jiguangInfo['jpush_app_key'], $jiguangInfo['jpush_master_secret'], $pushInfo['content'], $pushInfo['title'], $pushInfo['jiguang_id'], ['vod_id' => $pushInfo['vod_id']]);
                    break;
                case 'android':
                    $return = $this->sednjiaungAndroid($jiguangInfo['jpush_app_key'], $jiguangInfo['jpush_master_secret'], $pushInfo['content'], $pushInfo['title'], $pushInfo['jiguang_id'], ['vod_id' => $pushInfo['vod_id']]);
                    break;
            }
            //将返回结果写入数据库
            dump($return);
        }

    }

    /**
     * 检查更新数据，写入推送任务
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function checkVodUpdate()
    {
        //得到能够推送消息的appIDs
        $pushAppIds = db('banben')->where('can_push',1)->column('app_id');
        selfDump($pushAppIds);
        //查询最近更新的电视剧
        $list = db('vod')->where(['type_id|type_id_1' => ['in', [2, 3, 4]]])->whereTime('vod_time', '>=', time() - 7200)->order('vod_id', 'asc')->column('vod_name,vod_play_url,vod_remarks,vod_id', 'vod_id');
        dump(db('vod')->getLastSql());
//        dump($list);
//        dump(count($list));
        $vodIds = [];
        foreach ($list as &$vodInfo) {
            $vodIds[] = $vodInfo['vod_id'];
            //处理电影信息
            $playGroups = [];
            $playUrls = explode('$$$', $vodInfo['vod_play_url']);
            unset($vodInfo['vod_play_url']);
            foreach ($playUrls as $key => $jujiurl) {
                //解析url
                $jujis = explode('#', $jujiurl);
                $playList = [];
                foreach ($jujis as $juji) {
                    list($name, $url) = explode('$', $juji);
                    $playList[] = [
                        'name' => $name,
                        'url' => $url,
                    ];
                }
                $playGroups[] = count($playList);
            }

            $vodInfo['len'] = max($playGroups);
        }
//        dump(json_encode($vodIds,JSON_UNESCAPED_UNICODE));
//        dump(json_encode($list,JSON_UNESCAPED_UNICODE));

        $deviceLogs = db('openadlog')->whereIn('vod_id', $vodIds)->group('vod_id,app_id,device_id')->field('vod_id,vod_name,device_id,device_name,app_id,app_name')->whereIn('app_id',$pushAppIds)->where('memo', '历史记录')->where('vod_id', '>', 0)->whereNotNull('app_id')->where('app_id','<>','')->order('app_id', 'asc')->order('vod_id', 'asc')->select();
        selfDump(db('openadlog')->getLastSql());
        $jpushInfos = [];
        foreach ($deviceLogs as $deviceLog) {
            $deviceInfo = db('device')->where('device_id', $deviceLog['device_id'])->where('app_id', $deviceLog['app_id'])->cache('device_id_' . $deviceLog['device_id'], 3600)->find();
            //先查询jpush_job中有没有
            $jpushLog = db('push_job')->where('vod_id', $deviceLog['vod_id'])->where('app_id', $deviceInfo['app_id'])->where('device_id', $deviceInfo['device_id'])->order('time_added', 'desc')->find();
            if (empty($jpushLog) || $jpushLog['jishu'] < $list[$deviceLog['vod_id']]['len']) {
                $huashu = $this->getHuashu();
                $jpushInfos[] = [
                    "app_id" => $deviceInfo['app_id'],
                    "app_name" => $deviceInfo['app_name'],
                    "device_id" => $deviceInfo['device_id'],
                    "device_name" => $deviceInfo['device_name'],
                    "jiguang_id" => $deviceInfo['jiguang_id'],
                    "system_type" => $deviceInfo['system_type'],
                    "vod_id" => $deviceLog['vod_id'],
                    "vod_name" => $deviceLog['vod_name'],
                    "time_added" => time(),
                    "content" => str_replace(
                        ['{vod_name}', '{vod_remarks}'],
                        [$list[$deviceLog['vod_id']]['vod_name'], $list[$deviceLog['vod_id']]['vod_remarks']],
                        $huashu['content']
                    ),
                    "title" => str_replace(
                        ['{vod_name}', '{vod_remarks}'],
                        [$list[$deviceLog['vod_id']]['vod_name'], $list[$deviceLog['vod_id']]['vod_remarks']],
                        $huashu['title']
                    ),
                    'extra' => json_encode(['vod_id' => $deviceLog['vod_id']]),
                    'jishu' => $list[$deviceLog['vod_id']]['len'],
                    "status" => empty($deviceInfo['jiguang_id']) ? -1 : 0,//极光ID为空时直接不发消息
                ];

//                dump($huashu);
//                dump($list[$deviceLog['vod_id']]);
//                dump($jpushInfos);
//                exit;
            }

        }
        if (!empty($jpushInfos)) {
            db('push_job')->insertAll($jpushInfos, false, 200);
        }
        dump('写入成功，共计写入数据' . count($jpushInfos) . '条');
    }

    public function getHuashu()
    {
        $huashu = [
            [
                'title' => '小主，赶紧来观看吧，您关注的影片《{vod_name}》更新了',
                'content' => "影片《{vod_name}》{vod_remarks}"
            ],
            [
                'title' => '来不及了，《{vod_name}》更新了，赶紧去看',
                'content' => "影片《{vod_name}》{vod_remarks}"
            ],
            [
                'title' => '休闲时刻，《{vod_name}》更新了，快来观看！',
                'content' => "影片《{vod_name}》{vod_remarks}"
            ]
        ];

        shuffle($huashu);


        return array_pop($huashu);
    }

    public function doJpushJob()
    {
        $this->checkVodUpdate();
        $list = db('push_job')->where('status', 0)->select();
        if (!empty($list)) {
            $pushJobIds = array_column($list, 'id');
            //设置推送中
            db('push_job')->whereIn('id', $pushJobIds)->update(['status' => 1, 'pici' => time()]);

            foreach ($list as $pushJob) {

                $this->doSinglePush($pushJob['id'], $pushJob);
            }

        }

    }

    public function doSinglePush($id, $pushJob = [])
    {
//        $id = input('id');
        dump('当前传递的id为 ' . $id);
        if (empty($pushJob)) {
            $pushJob = db('push_job')->where('id', $id)->find();
        }
        if (empty($pushJob)) {
            return false;
        }

        //检查缓存影片信息
        $m3u8cacheCount = db('m3u8_cache')->where('vod_id', $pushJob['vod_id'])->where('is_cache','<>',0)->count();
        if (empty($m3u8cacheCount)) {
            $m3u8cacheCount = 0;
        }
        selfDump('本地缓存剧集数量'.$m3u8cacheCount);

        $m3u8cacheCountBj = db('m3u8_cache_bj')->where('vod_id', $pushJob['vod_id'])->where('is_cache','<>',0)->count();
        if (empty($m3u8cacheCountBj)) {
            $m3u8cacheCountBj = 0;
        }
        selfDump('八戒缓存剧集数量'.$m3u8cacheCountBj);
        $m3u8cacheCountOther = db('m3u8_cache_other')->where('vod_id', $pushJob['vod_id'])->where('is_need_deal',0)->count();
        if (empty($m3u8cacheCountOther)) {
            $m3u8cacheCountOther = 0;
        }
        selfDump('天堂缓存剧集数量'.$m3u8cacheCountBj);

        selfDump('天堂缓存剧集数量'.$m3u8cacheCountBj);

        $maxType = false;
        $maxCount = 0;
        if ($m3u8cacheCountOther >= $m3u8cacheCount && $m3u8cacheCountOther >= $m3u8cacheCountBj) {
            $maxType = 'other';
            $maxCount = $m3u8cacheCountOther;
        }elseif ($m3u8cacheCountBj >=$m3u8cacheCount && $m3u8cacheCountBj>=$m3u8cacheCountOther){
            $maxType = 'bj';
            $maxCount = $m3u8cacheCountOther;
        }elseif ($m3u8cacheCount >=$m3u8cacheCountBj && $m3u8cacheCount>=$m3u8cacheCountOther){
            $maxType = 'local';
            $maxCount = $m3u8cacheCount;
        }
        selfDump('剧集数'.$pushJob['jishu']);

        //如果存在缓存
        if($maxCount>0){
            if($maxCount<$pushJob['jishu']){
                selfDump('当前剧集尚未缓存');
                return '';
            }
        }


        $pushJob['extra'] = json_decode($pushJob['extra'], true);
        $pushJob['extra']['id'] = $pushJob['id'];
        $jiguangInfo = $this->jiguangAppIds[$pushJob['app_id']];
        //写入数据库
        switch ($pushJob['system_type']) {
            case 'ios':
//                        $pushJob['app_id'] = 'A6156623228930';
//                        $pushJob['jiguang_id'] = '18171adc03b41085da5';
//                        $jiguangInfo = $this->jiguangAppIds[$pushJob['app_id']];
                $return = $this->sednjiaungIOS($jiguangInfo['jpush_app_key'], $jiguangInfo['jpush_master_secret'], $pushJob['content'], $pushJob['title'], $pushJob['jiguang_id'], $pushJob['extra']);
                break;
            case 'android':
//                        $pushJob['app_id'] = 'A6158796075920';
//                        $pushJob['jiguang_id'] = '1507bfd3f778b808564';
//                        $jiguangInfo = $this->jiguangAppIds[$pushJob['app_id']];
                $return = $this->sednjiaungAndroid($jiguangInfo['jpush_app_key'], $jiguangInfo['jpush_master_secret'], $pushJob['content'], $pushJob['title'], $pushJob['jiguang_id'], $pushJob['extra']);
                break;
            default:
                break;
        }
        //处理return;
        dump(json_encode($return));

        db('push_job')->where('id', $pushJob['id'])->update([
            'status' => 2,
            'code' => $return['code'],
            'body' => json_encode($return['return']['body'])
        ]);


    }


    public function collectClickData()
    {
        $extra = input('extra/a');
        $id = $extra['id'];
        $vodId = $extra['vod_id'];
        if (empty($extra)) {
            $this->error('数据错误！');
        }
        sendDingding(json_encode($extra, JSON_UNESCAPED_UNICODE) . "\n" . $id, 'jpush');
        $find = db('push_job')->where('id', $id)->where('vod_id', $vodId)->find();
        if (!empty($find)) {
            db('push_job')->where('id', $find['id'])->update(['click_status' => 1]);
        }
        $this->success('获取成功！');
    }
}